package com.qf.first.controller;


import com.qf.first.entity.*;
import com.qf.first.exceptions.BaseException;
import com.qf.first.pojo.bo.Code;
import com.qf.first.pojo.bo.MyData;
import com.qf.first.pojo.vo.RespVo;
import com.qf.first.service.AdminService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;

@Api(tags = "管理员模块")
@RestController
@RequestMapping("/admin")
public class AdminController extends BaseController{
    @Autowired
    private AdminService adminService;
    @ApiOperation("检查用户是否为管理员")
    @GetMapping("/checkAdmin")
    public RespVo checkUser(User user){
            if (user==null){
                throw new BaseException(RespVo.CodeType.FAIL.getValue(),"信息不能为空");
            }
        User user1 = adminService.checkUser(user);
            if (user1==null){
                return convertFail("用户密码错误或改用户不是管理员");
            }
        return convertSuccess(user1);
    }

    @ApiOperation("修改密码")
    @GetMapping("/changePassword")
    public RespVo changePassword(User user){
        System.out.println(user);
        if (user==null){
            throw new BaseException(RespVo.CodeType.FAIL.getValue(),"数据不能为空");
        }
        int i = adminService.updateUser(user);
        if (i==0){
            return convertFail("密码修改失败");
        }
        return convertSuccess("密码修改成功");
    }
    @ApiOperation("登录功能")
    @GetMapping("/login")
    public RespVo login(Code code, User user, HttpSession session){
        Boolean flag = adminService.checkCode(code.getCode(), session);
        if (!flag){
            return convertFail("验证码错误");
        }
        User user1 = adminService.checkUser(user);
        if (user1==null){
            return convertFail("用户名或密码错误或该用户不是管理员");
        }
        session.setAttribute("id",user1.getUserId());
        return convertSuccess(user1);
    }

    @ApiOperation("获取系统数据")
    @GetMapping("/getData")
    public RespVo getData(){
        int shopNum = adminService.selectShop();
        int userNum = adminService.selectUser();
        List<Order> orders = adminService.selectOrder();
        int orderSum=orders.size();
        double allPrice = 0.0;
        for (int i = 0; i <orders.size() ; i++) {
            allPrice+=orders.get(i).getOrderAllPrice();
        }
        MyData myData = new MyData(shopNum,userNum,orderSum,allPrice,orders);
        return convertSuccess(myData);
    }
}
